package org.jdns.jfreechess.draw;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.prefs.Preferences;

import javax.swing.JFrame;
import javax.swing.JPanel;

import org.jdns.jfreechess.chess.ChessPiece;
import org.jdns.jfreechess.chess.ChessPiece.Color;
import org.jdns.jfreechess.chess.ChessPiece.Type;

/*
 * Copyright (C) 2012 James Ring (sjr@jdns.org)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

public class JChessBoard extends JPanel {
  private static final int BOARD_WIDTH = 8;
  private static final int BOARD_HEIGHT = 8;

  private ChessPiece[][] pieces = new ChessPiece[BOARD_WIDTH][BOARD_HEIGHT];

  private ChessPiece draggedPiece;
  private Point dragPoint;

  private final BoardPreferences preferences = new BoardPreferences(
      Preferences.userNodeForPackage(JChessBoard.class));

  public JChessBoard() {
    preferences.addBoardPreferenceListener(new BoardPreferenceListener() {
      @Override
      public void preferenceChanged() {
        repaint();
      }
    });

    MouseAdapter listener = new MouseAdapter() {
      ChessPiece piece = new ChessPiece(Type.KNIGHT, Color.WHITE);

      @Override
      public void mouseDragged(MouseEvent e) {
        draggedPiece = piece;
        dragPoint = e.getPoint();
        repaint();
      }

      @Override
      public void mouseReleased(MouseEvent e) {
        draggedPiece = null;
        dragPoint = null;
        repaint();
      }
    };

    addMouseMotionListener(listener);
    addMouseListener(listener);
  }

  @Override
  public void paint(Graphics g) {
    super.paint(g);

    Graphics2D g2 = (Graphics2D) g;

    int boardSideLength = Math.min(getWidth(), getHeight());
    int squareSideLength = boardSideLength / Math.max(BOARD_WIDTH, BOARD_HEIGHT);

    // i = 0 -> rank == 1
    for (int i = 0; i < BOARD_WIDTH; i++) {

      // j = 0 -> file == a
      for (int j = 0; j < BOARD_HEIGHT; j++) {
        drawSquare(g2, i, j, squareSideLength);

        if (pieces[i][j] != null) {
          ChessPiece piece = pieces[i][j];

          int x = i * squareSideLength;
          int y = (BOARD_HEIGHT - j - 1) * squareSideLength;

          preferences.getPieceSet().drawPiece(piece, g2, x, y, squareSideLength);
        }
      }

    }

    if (draggedPiece != null) {
      preferences.getPieceSet().drawPiece(draggedPiece, g2, dragPoint.x - squareSideLength / 2,
          dragPoint.y - squareSideLength / 2, squareSideLength);
    }
  }

  public void setPieceAt(int x, int y, ChessPiece piece) {
    pieces[x][y] = piece;
  }

  public void clearPieceAt(int x, int y) {
    setPieceAt(x, y, null);
  }

  private void drawSquare(Graphics2D g2, int i, int j, int squareWidth) {
    boolean isBlack = ((i % 2) + j) % 2 == 0;

    int x = i * squareWidth;
    int y = (BOARD_HEIGHT - j - 1) * squareWidth;

    g2.setColor(isBlack ? preferences.getBlackSquareColor() : preferences.getWhiteSquareColor());
    g2.fillRect(x, y, squareWidth, squareWidth);
  }

  @Override
  public Dimension getPreferredSize() {
    return new Dimension(60 * BOARD_WIDTH, 60 * BOARD_HEIGHT);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("Chess");
    frame.getContentPane().add(new JChessBoard());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}
